package mysql

import (
	"errors"

	"frame/global/variable"
	"frame/internal/app/user/domain"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

// UserRepository 用户仓储接口
type UserRepository interface {
	Save(user *domain.User) error
	FindByID(id string) (*domain.User, error)
}

// UserRepositoryImpl 用户仓储实现（例如：存储到内存或数据库）
type UserRepositoryImpl struct {
	*gorm.DB `gorm:"-" json:"-"`
	// 假设有数据库连接等字段
	users map[string]*domain.User
}

// NewUserRepository 创建一个新的仓储实例
func NewUserRepository() *UserRepositoryImpl {
	return &UserRepositoryImpl{
		DB:    UseDbConn(),
		users: make(map[string]*domain.User),
	}
}

// Save 保存用户
func (r *UserRepositoryImpl) Save(user *domain.User) error {
	r.users[user.ID] = user
	return nil
}

// FindByID 根据ID查询用户
func (r *UserRepositoryImpl) FindByID(id string) (*domain.User, error) {
	user, exists := r.users[id]
	if !exists {
		return nil, errors.New("user not found")
	}
	return user, nil
}

// FindHotelBindInfo 获取酒店绑定信息
func (r *UserRepositoryImpl) FindHotelBindInfo(where map[string]interface{}, dataAmount int, field string) (interface{}, error) {

	var userField []interface{}
	// 创建基本查询
	query := r.DB.Table("user AS u")

	// 构建筛选条件
	query = r.buildFilters(where, query, "h")
	query = query.Joins("INNER JOIN address AS address ON u.id = address.user_id")

	// 分页查询并做连接
	err := query.
		Offset(dataAmount).Limit(10).
		Select("u." + field).
		Order("u.id desc").
		Find(&userField).Error
	if err != nil {
		variable.ZapLog.Error("FindWithUserForCondition Find Error", zap.Error(err))
		return userField, err
	}

	return userField, nil

}
func (r *UserRepositoryImpl) buildFilters(filters map[string]interface{}, query *gorm.DB, alias string) *gorm.DB {
	for key, value := range filters {
		// 跳过空值
		if value == nil || value == "" {
			continue
		}

		whereKey := key
		if alias != "" {
			whereKey = alias + "." + key
		}

		switch key {
		case "status":
			// 处理单个整数值的字段
			if v, ok := value.(int); ok {
				query = query.Where(whereKey+" = ?", v)
			}
		case "name":
			// 模糊查询
			if v, ok := value.(string); ok {
				query = query.Where(whereKey+" LIKE ?", "%"+v+"%")
			}
		case "star", "type":
			// 处理 IN 查询
			if v, ok := value.([]int); ok && len(v) > 0 {
				query = query.Where(whereKey+" IN ?", v)
			}
		//case "priceRange":
		//	// 自定义字段区间查询
		//	if v, ok := value.(map[string]interface{}); ok {
		//		if low, ok := v["low"].(float64); ok {
		//			query = query.Where(whereKey+" >= ?", low)
		//		}
		//		if high, ok := v["high"].(float64); ok {
		//			query = query.Where(whereKey+" <= ?", high)
		//		}
		//	}
		default:
			// 打印调试日志
			variable.ZapLog.Info(key, zap.Any("value", value))
		}
	}
	return query
}
